package com.goodl.filter;

import com.goodl.pojo.User;
import com.goodl.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        String uri = request.getRequestURI();

        // 如果是 error.jsp 请求，直接放行，避免循环重定向
        if (uri.endsWith("/jsp/error.jsp")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/jsp/error.jsp");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
